import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Image, 
  Dimensions,ScrollView,Modal,TextInput,
  TouchableOpacity,
} from 'react-native';
import Orientation from 'react-native-orientation';
import ImagePicker from 'react-native-image-crop-picker';
import Toast, {DURATION} from 'react-native-easy-toast'
import SearchView from '../../component/SearchView';
import Loading from '../../component/Loading';
import {jumpPage} from '../../common/common'
import { TipModal } from '../../component/Tips';
import {BASEURL} from '../../api/api'
import NoData from '../../component/NoData';
import Search from './Search';
import BackButton from '../../component/BackButton';
import MyButton from '../../component/MyButton';
const {height, width} = Dimensions.get('window');
var IMG_URL =  BASEURL+'image/showImage?imageName=';

export default class Compound extends Component{
	static navigationOptions = ({ navigation }) =>{
    return{
      title: '封面标题',
      headerRight:(<View></View>),
      headerLeft:<BackButton navigation = {navigation}/>
    }
	};
  constructor(props){
    super(props);
    this.state = ({
      tempId: this.props.navigation.getParam('tempId'),
			userId: this.props.navigation.getParam('userId'),
			tempTitle: '',
			tempDesc: '',
			tempImg:this.props.navigation.getParam('tempImg'),
    })
  }
	componentWillMount() {
    Orientation.lockToPortrait();
  }
  componentWillUnmount() {
		
		Orientation.lockToLandscape();
  }
  _comp(){
		let {tempTitle, tempDesc} = this.state;
		if(!tempTitle){
			this.refs.toast.show("请输入模板标题");
			return;
		} else if(!tempDesc){
			this.refs.toast.show("请输入作品描述");
			return;
		}
    this.refs.tipModal._loading();
		fetch(BASEURL+'temp/compose?userId='+this.state.userId+'&tempId='
			+this.state.tempId+'&tempImg='+this.state.tempImg+'&tempTitle='+tempTitle+'&tempDesc='+tempDesc)
    .then(res => res.json())
    .then(result =>{
      this.refs.tipModal._close();
      if(result.succ == '1'){
        this.refs.tipModal._success('合成申请提交成功，请等待管理员审核',2500)
      } else {
        this.refs.tipModal._error('合成失败',2500)
      }
    })
	}
	_uploadImg(){
		ImagePicker.openPicker({
      width: 300,
      height: 300,
      cropping: false
    }).then(image => {
			console.log(image);
			if(image.path){
				this.uploadImage(image.path);
			}
    });
	}
	uploadImage(imagePath){
    var url = BASEURL+'image/uploadImage';
    var formData = new FormData();
    var fileName = imagePath.substring(imagePath.lastIndexOf("/")+1,imagePath.length);
    let file = {uri: imagePath, type: 'multipart/form-data', name: fileName};
    formData.append("file",file);
		formData.append("busType","2");
    fetch(url,{
      method:'POST',
      headers:{
          'Content-Type':'multipart/form-data',
      },
      body:formData,
    })
    .then((response) => response.json() )
    .then((responseData)=>{
			//alert(JSON.stringify(responseData));
      this.setState({
				tempImg: responseData.imageName
			})
    })
    .catch((error)=>{
      console.error('error',error);
      this.refs.toast.show("上传失败");
    });
  }
	_titleChange(val){
		this.setState({
			tempTitle: val
		})
	}
	_descChange(val){
		this.setState({
			tempDesc: val
		})
	}
	render(){
		let tempImg = IMG_URL+this.state.tempImg;
		//alert(tempImg)
		return(
			<View style={{flex:1,backgroundColor:'#f0f0f0'}}>
        <View style={styles.searchView}>
          <TextInput 
            ref={this.props._ref}
            placeholder='请输入模板标题'
            style={styles.searchInput}
            underlineColorAndroid="transparent"
            onChangeText={(val)=>{this._titleChange(val)}}
            onBlur={this.props.onBlur}
            value={this.props.val}
            returnKeyType='search'
          />
        </View>
				<View style={[styles.searchView,{height:100}]}>
          <TextInput 
						ref={this.props._ref}
						multiline={true}
						style={{height:100,padding:5}}
						textAlignVertical='top'
						underlineColorAndroid="transparent"
            placeholder='请做出作品描述'
            style={styles.searchInput}
            underlineColorAndroid="transparent"
            onChangeText={(val)=>{this._descChange(val)}}
            onBlur={this.props.onBlur}
            value={this.props.val}
            returnKeyType='search'
          />
        </View>
				{/* <View style={{justifyContent:'center',alignItems:'center',marginTop:20,
				backgroundColor:'white',paddingTop:20,paddingBottom:20}}>
					<Image style={{width:80,height:80}} source={require('../../images/temp/com_edit.png')}/>
					<Text style={{color:'#333'}}>自定义封面</Text>
				</View> */}
				<View style={{flexDirection:'row',justifyContent:'space-around',alignItems:'center',marginTop:20,
					backgroundColor:'white',paddingTop:20,paddingBottom:20}}>
					{this.state.tempImg?<Image resizeMode='cover' style={styles.img} source={{uri:tempImg}}/>:null}
					<TouchableOpacity onPress={()=>{this._uploadImg()}} style={{alignItems:'center'}}>
						<Image style={{width:80,height:80}} source={require('../../images/temp/com_edit.png')}/>
						<Text style={{color:'#333'}}>自定义封面</Text>
					</TouchableOpacity>
					
				</View>
				<View style={{flex:1}}></View>
				<View style={{flexDirection:'row',alignItems:'center',paddingLeft:10}}>
					<Image style={{width:20,height:20,}} source={require('../../images/temp/icon_sel.png')}/>
					<Text>允许动画工厂展示该作品</Text>
				</View>
        <TipModal ref="tipModal"/>
				<MyButton text='合成' btnStyle={{marginBottom:10}} press={()=>{this._comp()}}/>
				<Toast ref="toast" position='bottom' positionValue={200} />
			</View>
		)
	}
	
}
const styles = StyleSheet.create({
	img:{
		width:120,
		height:100,
		resizeMode:'cover'
	},
	searchView:{
		width:width,
		height:40,
		marginTop:20,
		paddingLeft:20,
		paddingRight:20,
	},
	searchInput:{
		backgroundColor:'white',
    padding:0,
    paddingLeft:5,
    flex:1,
    height: 36, 
    borderRadius:10
  },
})